import { inject, observer } from "mobx-react";
import React from "react";
import { Image, StyleSheet } from "react-native";
import BasePage from "./BasePage";
import { View } from "react-native-ui-lib";
import { commonStyles } from "../configs/commonStyle";
import { NavigationEvents } from "react-navigation";
import TabNavigator from "react-native-tab-navigator";
import Home from "./home/Home";
import SplashScreen from "react-native-splash-screen";
import Events from "../utils/events";
import { IconImage } from "../utils";
import MineIndex from "./mine/MineIndex";
import Features from "./features/Features";
import PermissionDialog from "./common/PermissionDialog";
import { start, stop } from "react-native-amap-geolocation";
import { checkLocationPermission, logger, uploadError } from "../utils/util";
import Recorder from "./components/Recorder";
import Player from "./components/Player";
import { toJS } from "mobx";
import moment from "moment";
// import VDebugPanel from "./common/VDebugPanel";
import { getSeekOrderCount } from "../plugins/SeekOrderNotification";
import { countTimeOrder, countComplaintOrder } from "../net/order";
import { uploadRecord } from "../net/common";

/**
 * 主页
 */
@inject("userStore", "appStore", "upgradeStore")
@observer
export default class MainPage extends BasePage {
  constructor(props) {
    super(props);
    this.isUploading = false;
    this.recorder = React.createRef();
    this.player = React.createRef();
    this.state = {
      selectedTab: 0,
      initTab: 0,
    };
  }

  componentDidMount() {
    super.componentDidMount();
    SplashScreen.hide();
    this.changeTabListener = Events.subscribe("UPLOAD_RECORD", data => this.uploadRecord());
    this.getLocation();
    this.addLocationListener();
    this.cleanErrorLog();
  }

  cleanErrorLog = () => {
    //清除日志保留超过7天的数据
    const { errorLog, setValue } = this.props.userStore;
    let list = toJS(errorLog);
    let now = moment().add(-7, "day").format("YYYY-MM-DD HH:mm:ss");
    // const tempList = list&&list.filter(data => moment(data.time).isAfter(now));
    logger("日志", list);
    // setValue("errorLog", tempList);
  };

  getLocation = async () => {
    let permissionResult = await checkLocationPermission();
    if (permissionResult == true) {
      start();
    } else {
      this.permissionDialog.show("需要根据您的位置获取所在城市，请开启位置权限");
    }
  };

  componentWillUnmount() {
    super.componentWillUnmount();
    this.changeTabListener && this.changeTabListener.remove();
    stop();
  }

  onDidFocus = () => {
    const { permissionList } = this.props.userStore
    this.props.upgradeStore.versionCheck();
    this.uploadRecord();
    this.getUnHandlerNum();
    if (permissionList && permissionList.includes('seekOrder')) {
      getSeekOrderCount();
    }
  };

  getUnHandlerNum = () => {
    const { setValue } = this.props.userStore;
    countTimeOrder({ token: global.token })
      .then(res => {
        if (!IsNullOrEmpty(res) && typeof res === "number") {
          setValue("timeOrderCount", res);
        }
      })
      .catch(e => {
        logger("超时订单未处理数量统计error", e);
      });

    countComplaintOrder({ token: global.token })
      .then(res => {
        if (!IsNullOrEmpty(res) && typeof res === "number") {
          setValue("complaintOrderCount", res);
        }
      })
      .catch(e => {
        logger("投诉订单未处理数量统计error", e);
      });
  };

  uploadRecord = () => {
    const { uploadFailList, userInfo } = this.props.userStore;
    if (this.isUploading == false && !IsNullOrEmpty(uploadFailList)) {
      logger("准备上传", this.isUploading);
      const upload = uploadFailList&& uploadFailList.find(data => data.distributorId == userInfo.distributorId);
      if (!IsNullOrEmpty(upload)) {
        logger("开始上传", upload);
        this.uploadFailRecord(uploadFailList, upload);
      }
    }
  };

  uploadFailRecord = (uploadList, upload) => {
    const { uploadFailList, setValue } = this.props.userStore;
    if (IsNullOrEmpty(upload.videoUri) || upload.videoUri == "Already stopped" || IsNullOrEmpty(upload.recordingNo)) {
      const tempList = uploadFailList.filter(data => data.recordingNo != upload.recordingNo);
      setValue("uploadFailList", tempList);
      logger("清理垃圾数据");
      this.toUpload(uploadList, upload);
      return;
    }
    logger("录音订单号", upload.recordingNo);
    this.isUploading = true;
    let paramsVideo = new FormData();
    paramsVideo.append("file", {
      uri: upload.videoUri,
      type: "audio/aar",
      name: upload.videoUri && upload.videoUri.substring(upload.videoUri.lastIndexOf("\/") + 1),
    });
    paramsVideo.append("order_no", upload.recordingNo);
    paramsVideo.append("track_length", upload.track_length || 0);
    paramsVideo.append("isDance", upload.isDance);
    paramsVideo.append("orderService", upload.orderService);
    uploadRecord(paramsVideo).then(res => {
      this.isUploading = false;

      if (res && !IsNullOrEmpty(res.key)) {
        logger("上传录音成功", res);
        const tempList = uploadFailList.filter(data => data.recordingNo != upload.recordingNo);
        setValue("uploadFailList", tempList);
        Events.publish("RefreshOrderList");
      } else {
        logger("上传失败,接口错误", res);
        uploadError(`调用上传失败1：${api.uploadRecord}`, `单号：${upload.recordingNo},\n${JSON.stringify(res)}`);
      }
      this.toUpload(uploadList, upload);
    })
      .catch(e => {
        this.isUploading = false;
        logger("上传失败", e);
        try {
          uploadError(`调用上传失败2：${api.uploadRecord}`, `单号：${upload.recordingNo},\n${JSON.stringify(e)}`);
        } catch (e) {
        }
        this.toUpload(uploadList, upload);
      })
  };

  toUpload = (uploadList, upload) => {
    const { userInfo } = this.props.userStore;
    const newList = uploadList.filter(data => data.recordingNo != upload.recordingNo);
    if (!IsNullOrEmpty(newList)) {
      const newUpload = newList.find(data => data.distributorId == userInfo.distributorId);
      if (!IsNullOrEmpty(newUpload)) {
        this.uploadFailRecord(newList, newUpload);
      }
    }
  };

  render() {
    const { showRecorder, showPlayer, showPage } = this.props.userStore;
    const { isDebug } = this.props.appStore;
    return (
      <View style={commonStyles.body}>
        <NavigationEvents onDidFocus={() => this.onDidFocus()} />
        <View flex>
          <TabNavigator
            style={styles.container}
            tabBarStyle={{ height: 52 }}
            tabBarShadowStyle={{ backgroundColor: "#EEEEEE" }}>
            <TabNavigator.Item
              selected={this.state.selectedTab === 0}
              tabStyle={{ backgroundColor: "white" }}
              title="配送"
              titleStyle={{ fontSize: 12 }}
              selectedTitleStyle={{ color: "#555555" }}
              renderIcon={() => (
                <Image
                  style={styles.tab_img}
                  source={IconImage.icon_home_normal}
                />
              )}
              renderSelectedIcon={() => (
                <Image
                  style={styles.tab_img}
                  source={IconImage.icon_home_checked}
                />
              )}
              onPress={() => this.setState({ selectedTab: 0 })}>
              <Home
                {...this.props}
                callBack={index => this.setState({ selectedTab: 1 })}
              />
            </TabNavigator.Item>
            <TabNavigator.Item
              selected={this.state.selectedTab === 1}
              tabStyle={{ backgroundColor: "white" }}
              title="功能"
              titleStyle={{ fontSize: 12 }}
              selectedTitleStyle={{ color: "#555555" }}
              renderIcon={() => (
                <Image
                  style={styles.tab_img}
                  source={IconImage.icon_data_normal}
                />
              )}
              renderSelectedIcon={() => (
                <Image
                  style={styles.tab_img}
                  source={IconImage.icon_data_checked}
                />
              )}
              onPress={() => this.setState({ selectedTab: 1 })}>
              <Features {...this.props} />
            </TabNavigator.Item>
            <TabNavigator.Item
              selected={this.state.selectedTab === 3}
              title="我的"
              titleStyle={{ fontSize: 12 }}
              tabStyle={{ backgroundColor: "white" }}
              selectedTitleStyle={{ color: "#555555" }}
              renderIcon={() => (
                <Image
                  style={styles.tab_img}
                  source={IconImage.icon_mine_normal}
                />
              )}
              renderSelectedIcon={() => (
                <Image
                  style={styles.tab_img}
                  source={IconImage.icon_mine_checked}
                />
              )}
              onPress={() => this.setState({ selectedTab: 3 })}>
              <MineIndex {...this.props} />
            </TabNavigator.Item>
          </TabNavigator>
          <View useSafeArea />
        </View>
        <PermissionDialog ref={r => this.permissionDialog = r} />
        {
          showRecorder && showPage == "main" ? <Recorder onRef={this.recorder} showRecorder={showRecorder} /> : null
        }
        {
          showPlayer && showPage == "main" ? <Player onRef={this.player} showPlayer={showPlayer} /> : null
        }
        {/* {isDebug ? <VDebugPanel/> : null} */}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  tab_img: { width: 23, height: 23 },
});
